package controller.sevlet.page;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Product;
import controller.dao.Dao_Category;
import controller.dao.Dao_Product;

public class shopCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		Dao_Category daoc = new Dao_Category();
		request.setAttribute("cats", daoc.listAll());
		
		Dao_Product daop = new Dao_Product();
		HttpSession session = request.getSession(false);
//		ShopCart sc = (ShopCart)session.getAttribute("shopCart");
		HashMap<String,Integer> shopCart= (HashMap<String,Integer>)session.getAttribute("shopCart");
		Set<String> IDs = shopCart.keySet();
		List<Product> products = new ArrayList<Product>();
		
		for(String ID : IDs){
			int i = Integer.parseInt(ID);
			products.add(daop.list(i));
		}
		
		request.setAttribute("prods", products);
//		for(Integer i: shopCart.values()){
//			response.getWriter().println(i);
//		}
		RequestDispatcher out = request.getRequestDispatcher("client/shop-cart.jsp");
		out.forward(request, response);
	}
	
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(false);
//		ShopCart sc = (ShopCart)session.getAttribute("shopCart");
		HashMap<String,Integer> shopCart = (HashMap<String,Integer>) session.getAttribute("shopCart");
		String prodId = request.getParameter("codprod");
		int quantity = Integer.parseInt(request.getParameter("quantity"));
		shopCart.put(prodId,quantity);
		session.setAttribute("shopCart", shopCart);
		
		response.sendRedirect("index.jsp");
	}

}
